//
//  SearchShopViewController.m
//  SafeFoodManagerDemo
//
//  Created by ios-1 on 2018/3/14.
//  Copyright © 2018年 bob. All rights reserved.
//

#import "SearchShopViewController.h"
#import "RightShopTableViewCell.h"
#import "GetRegisterInforModel.h"
#import "AddRecruitViewController.h"
#import "HelpDetailViewController.h"
#import "AddAcountViewController.h"
#import "HelpListModel.h"
#import "GoodListModel.h"
@interface SearchShopViewController ()
@property(nonatomic,copy)NSString*SearchKeyWord;
@property(nonatomic,copy)NSString*positionId;      //当前岗位ID
@property(nonatomic,copy)NSString*shopId;          //当前岗位商户ID
@property(nonatomic,assign)BOOL is_selectPosition; //是否点击当前岗位
@end

@implementation SearchShopViewController

- (void)viewDidLoad {
    
  
    [super viewDidLoad];
    
    self.homeTableView.estimatedRowHeight=70;
    [self.homeTableView registerNib:[UINib nibWithNibName:@"RightShopTableViewCell" bundle:nil] forCellReuseIdentifier:@"RightShopCell"];
    [self.homeTableView.mj_header beginRefreshing];
    self.homeTableView.tableHeaderView = [self tabHeadView];
    
    [self addNavigationItemWithTitles:@[@"返回"] isLeft:YES target:self action:@selector(backBtnClicked) tags:nil];
    
//    [self.view addSubview:self.Footview];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    DLog("控制器出现++++++");
    
    
}
- (UIView*)tabHeadView
{
    UIView *headview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.1)];
    headview.backgroundColor = [UIColor clearColor];
    
    return headview;
}
#pragma mark-tablevie代理方法

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    GoodListData *data=self.dataArr[indexPath.row];
    
    RightShopTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"RightShopCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.addCartBlock = ^(NSInteger count, BOOL add) {
        data.quantity = count;
    };
    cell.addCartBlock1 = ^(float count, BOOL add) {
        data.quantity = count;
    };
    
    
    
    
    cell.priceChangeBlock1=^(float count, NSInteger index){
        
        if (self.is_Out) {
            data.salePrice = count;
        }else{
            
            data.price = count;
            
        }
        
       
        
    };
    
    [cell refreshData:data ISOut:self.is_Out];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    return UITableViewAutomaticDimension;
    return 60;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

-(void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section
{
    
    view.tintColor=TBColorTableViewBg;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 0.1;
    
}

#pragma mark-搜索跳转事件
-(void)PushChangeStatueVC
{
    BOOL isSelf=self.Reqmodel.shopId==0?YES:NO;
    
    BaseSearchChooseViewController *Choose=[[BaseSearchChooseViewController alloc]init];
    
    if (isSelf) {
        
//        if ([self.Reqmodel.ptype isEqualToString:@"1"]) {
//
//            Choose.CustomArr=[SearchAndChooseManager GetChooseDateWithType:AdditiveListType andIsLookSelf:isSelf];
//
//        }else if ([self.Reqmodel.ptype isEqualToString:@"2"])
//        {
//
//            NSArray *PostArr= [USER_DEFAULT objectForKey:@"TBChoose"];//如果本地存在则读取本地的
//
//            if (PostArr.count!=0) {
//
//                Choose.CustomArr=PostArr;
//
//            }else{
//
//                Choose.CustomArr=@[@{@"fieldName":@"marketIds",@"name":@"开办方",@"value":@""},@{@"fieldName":@"type",@"name":@"",@"value":@""},@{@"fieldName":@"checkUserIds",@"name":@"检查员",@"value":@""},@{@"fieldName":@"startDate",@"name":@"开始日期",@"value":@""},@{@"fieldName":@"endDate",@"name":@"结束日期",@"value":@""}];
//            }
//        }
        
    }else{
        
//        Choose.CustomArr=[SearchAndChooseManager GetChooseDateWithType:PatrolListType andIsLookSelf:isSelf];
    }
    Choose.SearchPlace=self.searchName;
    
    Choose.KeyWord=self.SearchKeyWord;
    
    Choose.Lshopid=self.Reqmodel.shopId;
    
    Choose.SureBlock=^(NSString *paras,NSString*keyword)
    {
        
        self.SearchKeyWord=keyword;
        
        NSDictionary* params=[NSMutableDictionary dictionary];
        [params setValue:[NSString stringWithFormat:@"%ld",self.Reqmodel.supplierId] forKey:@"supplierId"];
        [params setValue:[NSString stringWithFormat:@"%@",keyword] forKey:@"keyword"];
        self.Reqmodel.params = [HelpWay dictionaryToJSON:params];
        
        [self.homeTableView.mj_header beginRefreshing];
    };
    
    [self.navigationController pushViewController:Choose animated:YES];
}

#pragma mark-新增事件
-(void)addNewgoods
{
    
    
    if(self.addCartBlock)
    {
        
        
        self.addCartBlock(self.dataArr);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark-空白页点击事件
- (void)actionTapEmptyDataSetNodataView
{
    [self.homeTableView.mj_header beginRefreshing];
}

#pragma mark-返回上一层
- (void)backBtnClicked
{
   
    
    if(self.addCartBlock)
    {
        self.addCartBlock(self.dataArr);
    }
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  MJ头部刷新(封装层方法, 需要子类继承或者重写)
 */
- (void)actionMJHeaderRefresh
{
    self.Reqmodel.currentPage=1;
    
    [self.homeTableView.mj_footer resetNoMoreData];
    
    [self loadDatas];
    
//    if(!self.dataArr.count)
//    {
//        [self loadDatas];
//    }else{
//        [self NetRequestSuccess:self scrollView:self.homeTableView];
//    }
}

/**
 *  MJ底部加载(封装方法, 需要子类继承或者重写)
 */
- (void)actionMJFooterLoadMore
{
    self.Reqmodel.currentPage++;
    [self loadDatas];
    
//    if(!self.dataArr.count)
//    {
//        [self loadDatas];
//    }else{
//        [self NetRequestSuccess:self scrollView:self.homeTableView];
//    }
}

-(void)loadDatas
{
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/productList.json" andrequestTime:5 andParams:self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        GoodListModel *InforModel=[GoodListModel mj_objectWithKeyValues:responseObject];
        
        
        if (responseStatus==1) {
            //请求成功
            
            NSLog(@"%@",[HelpWay dictionaryToJSON:responseObject]);
        
            self.TotalNum=[NSString stringWithFormat:@"一共找到%ld个%@",[responseObject[@"totalRecord"]integerValue],@"商品"];
            if (InforModel.data.count==0&&self.Reqmodel.currentPage==1) {
                
                [self.dataArr removeAllObjects];
                
                [self.homeTableView reloadData];
                
                self.Type=TBNODateType;
                
                if (self.deleStatue) {
                    //如果处于删除状态
                    [self GotoEdit:self.btn];
                }
                
                self.btn.hidden=YES;
                
            }else if (InforModel.data.count==0&&self.Reqmodel.currentPage!=1){
                
                self.btn.hidden=NO;
                [self.homeTableView.mj_footer endRefreshingWithNoMoreData];
                
            } else{
                
                self.btn.hidden=NO;
                
                if (self.Reqmodel.currentPage==1) {
                    
                    [self.dataArr removeAllObjects];
                    
                }
                
                NSMutableArray *Array = [NSMutableArray array];
                
                [Array addObjectsFromArray:InforModel.data];
                
                
                [self handleData:Array];
                
//                [self.dataArr addObjectsFromArray:InforModel.data];
//                [self.homeTableView reloadData];
            }
            
            
            
            
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            if (self.Reqmodel.currentPage>1) {
                
                self.Reqmodel.currentPage=self.Reqmodel.currentPage-1;
            }
            
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
}

- (void)handleData:(NSMutableArray*)dataArray
{
    for(GoodListData *data in dataArray)
    {
        for(GoodListData *editdata in self.editArray)
        {
            if(data.goodsId == editdata.goodsId)
            {
                data.quantity = editdata.quantity;
            }
        }
        [self.dataArr addObject:data];
    }
    
    [self.homeTableView reloadData];
}
//-(void)loadDatas
//{
//    [self showLoadingAnimation];
//
//    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/additiveList.json" andrequestTime:5 andParams:self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
//
//    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
//        [self stopLoadingAnimation];
//
//        HelpListModel *InforModel=[HelpListModel mj_objectWithKeyValues:responseObject];
//
//        if (responseStatus==1) {
//            //请求成功
//
//            self.TotalNum=[NSString stringWithFormat:@"一共找到%ld个%@",InforModel.data.count,@"记录"];
//
//            if (InforModel.data.count==0&&self.Reqmodel.currentPage==1) {
//
//                [self.dataArr removeAllObjects];
//
//                self.Type=TBNODateType;
//
//                [self.homeTableView reloadData];
//
//            }else if (InforModel.data.count==0&&self.Reqmodel.currentPage!=1){
//
//                self.btn.hidden=NO;
//                [self.homeTableView.mj_footer endRefreshingWithNoMoreData];
//
//            } else{
//
//                self.btn.hidden=NO;
//
//                if (self.Reqmodel.currentPage==1) {
//
//                    [self.dataArr removeAllObjects];
//
//                }
//
//                [self.dataArr addObjectsFromArray:InforModel.data];
//
//                [self.homeTableView reloadData];
//
//            }
//
//            [self NetRequestSuccess:self scrollView:self.homeTableView];
//
//        }else if (responseStatus==0||responseStatus==2)
//        {
//            if (self.Reqmodel.currentPage>1) {
//
//                self.Reqmodel.currentPage=self.Reqmodel.currentPage-1;
//            }
//
//            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
//
//            self.Type=TBReqFalie;
//
//        }else{
//            //404需要重新登录了
//
//            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
//
//                if (buttonIndex==1) {
//
//                    [self GotoLoginVC];
//                }
//
//            }];
//        }
//
//    }];
//}

//- (UIView*)Footview
//{
//    if(_Footview == nil)
//    {
//        _Footview = [[UIView alloc]init];
//
//        if (kDevice_Is_iPhoneX) {
//
//            _Footview.frame=CGRectMake(0, SCREEN_HEIGHT-45*SCREEN_WIDTH/320-64-34, SCREEN_WIDTH, 45*SCREEN_WIDTH/320);
//        }else{
//            _Footview.frame=CGRectMake(0, SCREEN_HEIGHT-45*SCREEN_WIDTH/320-64, SCREEN_WIDTH, 45*SCREEN_WIDTH/320);
//        }
//        _Footview.backgroundColor = [UIColor whiteColor];
//
//        UILabel *totalMoneyLab = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, CGRectGetWidth(_Footview.frame)-100, CGRectGetHeight(_Footview.frame)/2)];
//        totalMoneyLab.text = @"合计：0";
//        totalMoneyLab.textColor = [UIColor redColor];
//        totalMoneyLab.font = [UIFont systemFontOfSize:14];
//
//        UILabel *totalCountLab = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetHeight(_Footview.frame)/2, CGRectGetWidth(_Footview.frame)-100, CGRectGetHeight(_Footview.frame)/2)];
//        totalCountLab.text = @"品种数量：0";
//        totalCountLab.textColor = [UIColor darkGrayColor];
//        totalCountLab.font = [UIFont systemFontOfSize:14];
//
//        UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        nextBtn.backgroundColor = TBColorAppTheme;
//        nextBtn.enabled = YES;
//        nextBtn.frame = CGRectMake(CGRectGetMaxX(totalMoneyLab.frame), 0, 90, CGRectGetHeight(_Footview.frame));
//        [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
//        [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        nextBtn.titleLabel.font = [UIFont systemFontOfSize:16];
//        [nextBtn addTarget:self action:@selector(nextClick:) forControlEvents:UIControlEventTouchUpInside];
//
//        [_Footview addSubview:totalMoneyLab];
//        [_Footview addSubview:totalCountLab];
//        [_Footview addSubview:nextBtn];
//    }
//    return _Footview;
//}

- (void)nextClick:(UIButton*)sender
{
    
    GetRegisterInforModel *model=[GetRegisterInforModel new];
    
    model.shopId=[NSString stringWithFormat:@"%ld",[LoginStatuesModel shopId]];
    
    model.token=[LoginStatuesModel getUserToken];
    
    AddAcountViewController *addPeople=[AddAcountViewController new];
    
    addPeople.requrl=@"/index.php/FoodCheckApi/ledgerInNewAddInfo.json";
    
    addPeople.Reqmodel=model;
    
    addPeople.postUrl=@"/index.php/FoodCheckApi/ledgerInNewAdd.json";
    
    addPeople.title=@"新增进货台账";
    
    addPeople.BtnStr=@"新增";
    
    addPeople.OptionSussStr=@"新增成功";
    
    addPeople.block=^()
    {
        [self.homeTableView.mj_header beginRefreshing];
    };
    
    [self.navigationController pushViewController:addPeople animated:YES];
}

- (NSMutableArray*)editArray
{
    if(_editArray==nil)
    {
        _editArray = [NSMutableArray array];
    }
    return _editArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
